package game.map
{
	import game.manager.MapManager;
	import game.VO.TileVO;
	import starling.display.Sprite;
	import starling.events.Event;
	
	/**
	 * ...
	 * @author Kirill Pletnev
	 */
	public class MapTilesContainer extends Sprite
	{
		private var _visualMap:VisualMap;
		private var _tiles:Vector.<Tile>;
		private var _numTilesInit:uint = 0;		
		private var _isInit:Boolean = false;
		
		public function MapTilesContainer(visualMap:VisualMap)
		{
			this.dispose();
			this._visualMap = visualMap;
			this._tiles = new Vector.<Tile>(visualMap.numColumns * visualMap.numRows);
		}
		
		public function initMapTiles():void
		{
			if (MapManager.instance.numTiles == 0)
			{
				_isInit = true;
				SplashScreen.instance.nextStep();
				trace("MapTilesContainer initialized");
				dispatchEvent(new Event(Event.COMPLETE));
				return;
			}
			
			var tile:Tile;
			for each (var tileVO:TileVO in MapManager.instance.mapTiles)
			{
				if (tileVO != null)
				{
					tile = new Tile(this, tileVO);
					tile.addEventListener(Event.COMPLETE, onMapTilesInit);
					tile.setTileOnMap();
					var tileIndex:int = PhysicalMap.getTileIndex(tileVO.columnPosition, tileVO.rowPosition, _visualMap.numColumns, _visualMap.numRows);
					this._tiles[tileIndex] = tile;
				}
			}
		}
		
		public function addTile(tileVO:TileVO):void
		{
			var tileIndex:int = PhysicalMap.getTileIndex(tileVO.columnPosition, tileVO.rowPosition, _visualMap.numColumns, _visualMap.numRows);
			if (tileIndex != -1)
			{
				if (_tiles[tileIndex] != null)
				{
					removeTile(tileIndex);
				}
				
				MapManager.instance.addMapTile(tileVO);
				var tile:Tile = new Tile(this, tileVO);
				tile.addEventListener(Event.COMPLETE, onTileAdded);
				_tiles[tileIndex] = tile;
				
				this.unflatten();
				tile.setTileOnMap();
			}
		}
		
		public function removeTile(tileIndex:int):void
		{
			if (tileIndex != -1)
			{
				var tile:Tile = _tiles[tileIndex];
				
				if (tile != null)
				{
					this.unflatten();
					tile.removeTileFromMap();
					_tiles[tileIndex] = null;
					MapManager.instance.removeMapTile(tileIndex);				
					this.flatten();
				}
			}
		}
		
		private function onTileAdded(event:Event):void
		{
			this.flatten();
			removeListenersComplete();
		}
		
		private function onMapTilesInit(event:Event):void
		{
			_numTilesInit++;
			
			if (MapManager.instance.numTiles == _numTilesInit)
			{
				this.flatten();
				removeListenersComplete();
				_isInit = true;
				SplashScreen.instance.nextStep();
				trace("MapTilesContainer initialized");
				dispatchEvent(new Event(Event.COMPLETE));
			}
		}
		
		private function removeListenersComplete():void
		{
			for each (var tile:Tile in _tiles)
			{
				if (tile != null)
				{
					tile.removeEventListeners(Event.COMPLETE);
				}
			}
		}
		
		public function get isInit():Boolean
		{
			return _isInit;
		}
	
	}

}